//
//  SensorUtil.swift
//  Pods
//
//  Created by HONOR on 2025/5/7.
//

import UIKit
import AVFoundation

class SensorUtil: NSObject {
    
    static let shared = SensorUtil()
        
    // MARK: - 私有化初始化方法
    private override init() {
        super.init()
    }
    
    // MARK: - 屏幕控制部分
    private var isScreenOff = false
    
    /// 保持屏幕常亮
    private func keepScreenOn() {
        UIApplication.shared.isIdleTimerDisabled = true
    }
    
    /// 允许屏幕自动锁定
    private func allowScreenSleep() {
        UIApplication.shared.isIdleTimerDisabled = false
    }
    
    /// 设置屏幕关闭（通过亮度调节模拟）
    private func setScreenOff() {
        guard !isScreenOff else { return }
        isScreenOff = true
        
        // 保存当前亮度
        let currentBrightness = UIScreen.main.brightness
        UserDefaults.standard.set(currentBrightness, forKey: "originalBrightness")
        
        // 设置最低亮度（接近关闭效果）
        UIScreen.main.brightness = 0.01
    }
    
    /// 恢复屏幕亮度
    private func setScreenOn() {
        guard isScreenOff else { return }
        isScreenOff = false
        
        // 恢复原始亮度
        let originalBrightness = UserDefaults.standard.value(forKey: "originalBrightness") as? CGFloat ?? 0.5
        UIScreen.main.brightness = originalBrightness
    }
    
    // MARK: - 接近传感器部分
    private var isProximityMonitoringEnabled = false
    private var isNear = false
    
    /// 启动接近传感器监听
    func startProximityMonitoring() {
        guard !isProximityMonitoringEnabled else { return }
        
        UIDevice.current.isProximityMonitoringEnabled = true
        
        if UIDevice.current.isProximityMonitoringEnabled {
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(proximityStateChanged),
                name: UIDevice.proximityStateDidChangeNotification,
                object: nil
            )
            isProximityMonitoringEnabled = true
        }
        
    }
    
    /// 停止接近传感器监听
    func stopProximityMonitoring() {
        guard isProximityMonitoringEnabled else { return }
        
        UIDevice.current.isProximityMonitoringEnabled = false
        NotificationCenter.default.removeObserver(
            self,
            name: UIDevice.proximityStateDidChangeNotification,
            object: nil
        )
        SpeakerUtil.releaseAudioSession()
        isProximityMonitoringEnabled = false
    }
    
    func initSpeaker(){
        if isNear {
            SpeakerUtil.switchToVoiceChatMode(useSpeaker: false)
        }else{
            SpeakerUtil.switchToMediaPlayback()
        }
    }
    
    func getNear() -> Bool {
        return isNear
    }
    
    func switchSpeaker(enable: Bool) {
        if !enable {
            isNear = true
            SpeakerUtil.switchToVoiceChatMode(useSpeaker: false)
        }else{
            isNear = false
            SpeakerUtil.switchToMediaPlayback()
        }
    }
    
    @objc private func proximityStateChanged() {
        if UIDevice.current.proximityState {
            print("设备靠近耳朵")
            setScreenOff()
            SpeakerUtil.switchToVoiceChatMode(useSpeaker: false)
            
            isNear = true
            
            SpeechPlayHelper.shared.onSwitchSpeaker(status: false)
        } else {
            print("设备离开耳朵")
            setScreenOn()
            SpeakerUtil.switchToMediaPlayback()
            
            isNear = false
            
            SpeechPlayHelper.shared.onSwitchSpeaker(status: true)
            
        }
    }
    
    
    
    // MARK: - 生命周期管理
    deinit {
        stopProximityMonitoring()
        allowScreenSleep()
        setScreenOn()
    }
}
